import 'package:flutter/material.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

class IndexPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  static int a  = 1;
  MqttServerClient client =
      MqttServerClient.withPort('192.168.100.230', '001', 1883);

  //初始化
  @override
  void initState() {
    //设置mqtt参连接相关参数
    client.onConnected = onConnected; //连接成功回调
    client.onDisconnected = onDisconnected; //连接断开回调
    client.onSubscribed = onSubscribed; //订阅成功回调
    client.onSubscribeFail = onSubscribeFail; //订阅失败回调
    client.onUnsubscribed = onUnsubscribed as UnsubscribeCallback?; //取消订阅回调
    client.pongCallback = pong; //收到 PING 响应回调

    client.logging(on: false); //设置是否登陆
    client.connect(); //连接，这里不需要异步

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MqTT'),
        ),
        body: Center(child: FormData()),
      ),
    );
  }

  TextEditingController _controller = new TextEditingController();
  TextEditingController _formFieldController = new TextEditingController();
  GlobalKey formKey = new GlobalKey<FormState>();

  Widget FormData() {
    return Form(
        /* globalKey, 用于后面获取FormState*/
        key: formKey,
        /* 开启自动效验 */
        autovalidate: true,
        child: Column(children: <Widget>[
          TextFormField(
            autofocus: false,
            cursorColor: Colors.green,
            keyboardType: TextInputType.text,
            //键盘输入类型(七种类型)
            textInputAction: TextInputAction.next,
            //键盘动作按钮图标
            controller: _controller,
            // maxLength: 18,
            //最大位数
            maxLengthEnforced: false,
            //超出maxLength,禁止输入
            decoration: InputDecoration(
              hintText: "订阅主题",
              icon: new Icon(
                Icons.message_rounded,
                size: 30,
              ),
            ),
            onChanged: (v) {
              //监听输入框值变化
            },
            /* 效验用户名 */
            validator: (v) {
              return v.toString().length <= 0 ? '订阅主题' : null;
            },
          ),
          TextFormField(
            autofocus: false,
            cursorColor: Colors.green,
            controller: _formFieldController,
            // maxLength: 18,
            maxLengthEnforced: false,
            obscureText: false,
            //密码输入类型
            decoration: InputDecoration(
                hintText: "消息",
                icon: Icon(
                  Icons.mark_chat_read,
                  size: 30,
                )),
          ),
          Padding(
              padding: EdgeInsets.only(top: 40.0),
              child: Row(children: <Widget>[
                Expanded(
                  child: RaisedButton(
                    padding: EdgeInsets.all(12.0),
                    color: Colors.green,
                    textColor: Colors.white,
                    child: Text('执行', style: TextStyle(fontSize: 17)),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(80.0) //设置圆角
                        ),
                    onPressed: () {
                      if ((formKey.currentState as FormState).validate()) {
                        if (_controller.text == 'false') {
                          close();
                        }
                        if (_controller.text == 'del') {
                          del(_formFieldController.text);
                        }
                        Message(_controller.text, _formFieldController.text);
                        // put();
                      }
                    },
                  ),
                ),
              ])),
        ]));
  }

  //页面销毁时关闭连接
  @override
  void dispose() {
    client.onDisconnected(); //断开连接
    super.dispose();
  }

  void close() {
    client.onDisconnected();
  }

  void del(zt) {
    client.onUnsubscribed(zt);
  }

  void put(String zt, String xx) {
    // log('主题' + zt);
    // log('消息' + xx);
    // const pubTopic = zt;
    final builder = MqttClientPayloadBuilder();
    builder.addString(xx);
    client.publishMessage(zt, MqttQos.atLeastOnce, builder.payload);
  }

  //消息监听
  void Message(zt,xx) async {
    try {
     var data =  this.client.getSubscriptionsStatus("rf/#1");
     if(data.toString().indexOf('active')==-1){
       //订阅主题
       await this.client.subscribe("rf/#", MqttQos.atLeastOnce);
     }

      //消息发布
      // const pubTopic = 'chenhaiwei'; //发布消息的主题
      final builder = MqttClientPayloadBuilder();
      builder.addString(xx); //发布的内容
      await client.publishMessage(zt, MqttQos.atLeastOnce, builder.payload);

      //取消订阅
       client.onUnsubscribed(zt);

      //监听消息
      client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
        var recMess = c![0].payload as MqttPublishMessage;
        var pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message!);
        print('消息:$pt,主题: <${c[0].topic}>');
      });
    } catch (e, stack) {
      print(e);
      print(stack);
    }
  }
}

void onConnected() {
  print('连接成功');
}

// 连接断开
void onDisconnected() {
  print('连接断开');
}

// 订阅主题成功
void onSubscribed(String topic) {
  print('订阅主题$topic成功');
}

// 订阅主题失败
void onSubscribeFail(String topic) {
  print('订阅主题 $topic失败');
}

// 成功取消订阅
void onUnsubscribed(String topic) {
  print('成功取消$topic主题订阅');
}

// 收到 PING 响应
void pong() {
  print('收到 PING 响应');
}
